package com.keyroy.game.puzzle_rpg.views;

import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.widgets.Composite;

import com.keyroy.game.puzzle_rpg.models.animations.TilesAnimationUtil;
import com.keyroy.game.puzzle_rpg.models.interfaces.AnimationListener;
import com.keyroy.game.puzzle_rpg.models.interfaces.Repaintable;
import com.keyroy.game.puzzle_rpg.models.interfaces.TilesListener;
import com.keyroy.game.puzzle_rpg.models.puzzle.PuzzleMap;
import com.keyroy.game.puzzle_rpg.models.puzzle.PuzzleUtil;
import com.keyroy.game.puzzle_rpg.models.puzzle.Result;
import com.keyroy.game.puzzle_rpg.models.render.PuzzleMapRender;

public class PuzzleView extends Composite implements Repaintable {
	PuzzleMap puzzleMap;
	PuzzleMapRender puzzleMapRender;
	TilesListener tilesListener;

	public PuzzleView(Composite parent) {
		super(parent, SWT.DOUBLE_BUFFERED);
		tilesListener = new TilesListener() {

			@Override
			public void onComplete() {

			}

			@Override
			public void onClean(List<Result> results) {

			}
		};

		addPaintListener(new PaintListener() {

			@Override
			public void paintControl(PaintEvent event) {
				if (puzzleMapRender != null) {
					puzzleMapRender.onDraw(event.gc);
				}
			}
		});

		addMouseListener(new MouseListener() {

			@Override
			public void mouseUp(MouseEvent e) {
				mouseDown(e);
			}

			@Override
			public void mouseDown(MouseEvent e) {
				if (puzzleMap != null) {
					PuzzleUtil.getPointerAction(tilesListener).pointerDown(puzzleMap, e.x, e.y);
				}
			}

			@Override
			public void mouseDoubleClick(MouseEvent e) {

			}
		});
	}

	public void setPuzzleMap(PuzzleMap puzzleMap) {
		if (puzzleMap != null) {
			this.puzzleMap = puzzleMap;
			this.puzzleMapRender = new PuzzleMapRender(puzzleMap);
			TilesAnimationUtil.init(this, this.puzzleMap);
			TilesAnimationUtil.startMove(new AnimationListener() {
				@Override
				public void onStart() {
				}

				@Override
				public void onComplete() {
				}
			});
		}

		setSize(puzzleMap.getWidth(), puzzleMap.getHeight());
	}

	@Override
	protected void checkSubclass() {
	}

	@Override
	public void repaint() {
		getDisplay().asyncExec(new Runnable() {
			@Override
			public void run() {
				redraw();
			}
		});
	}

}
